import React, { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import {
  MagnifyingGlassIcon,
  FunnelIcon,
  StarIcon,
  ArrowDownTrayIcon,
  EyeIcon,
  ClockIcon,
  FireIcon,
  SparklesIcon
} from '@heroicons/react/24/outline'
import { AppDispatch } from '@/store'
import { fetchPlugins, selectPlugins, selectPluginsLoading } from '@/store/slices/pluginSlice'
import { Card, Button, Input, Badge, StatusBadge, LoadingSkeleton } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

export const MarketplacePage: React.FC = () => {
  const { t } = useTranslation()

  const categories = [
    { id: 'all', nameKey: 'marketplace.categories.all', icon: '🔧' },
    { id: 'development', nameKey: 'marketplace.categories.development', icon: '💻' },
    { id: 'productivity', nameKey: 'marketplace.categories.productivity', icon: '⚡' },
    { id: 'utilities', nameKey: 'marketplace.categories.utilities', icon: '🛠️' },
    { id: 'entertainment', nameKey: 'marketplace.categories.entertainment', icon: '🎮' },
    { id: 'education', nameKey: 'marketplace.categories.education', icon: '📚' },
    { id: 'business', nameKey: 'marketplace.categories.business', icon: '💼' },
    { id: 'graphics', nameKey: 'marketplace.categories.graphics', icon: '🎨' },
    { id: 'communication', nameKey: 'marketplace.categories.communication', icon: '💬' },
    { id: 'security', nameKey: 'marketplace.categories.security', icon: '🔒' }
  ]

  const sortOptions = [
    { value: 'downloads', labelKey: 'marketplace.sort.mostDownloaded' },
    { value: 'rating', labelKey: 'marketplace.sort.highestRated' },
    { value: 'updated', labelKey: 'marketplace.sort.recentlyUpdated' },
    { value: 'created', labelKey: 'marketplace.sort.newest' },
    { value: 'name', labelKey: 'marketplace.sort.nameAZ' }
  ]
  const dispatch = useDispatch<AppDispatch>()
  const plugins = useSelector(selectPlugins)
  const isLoading = useSelector(selectPluginsLoading)
  const [searchParams, setSearchParams] = useSearchParams()

  // Local state
  const [searchTerm, setSearchTerm] = useState(searchParams.get('search') || '')
  const [selectedCategory, setSelectedCategory] = useState(searchParams.get('category') || 'all')
  const [sortBy, setSortBy] = useState(searchParams.get('sort') || 'downloads')
  const [showFilters, setShowFilters] = useState(false)

  useEffect(() => {
    // Update URL params
    const params = new URLSearchParams()
    if (searchTerm) params.set('search', searchTerm)
    if (selectedCategory !== 'all') params.set('category', selectedCategory)
    if (sortBy !== 'downloads') params.set('sort', sortBy)
    setSearchParams(params)

    // Fetch plugins with filters
    dispatch(fetchPlugins({
      search: searchTerm,
      category: selectedCategory === 'all' ? undefined : selectedCategory,
      page: 1,
      limit: 20
    }))
  }, [dispatch, searchTerm, selectedCategory, sortBy, setSearchParams])

  const featuredPlugins = (plugins || []).filter(plugin => plugin.featured).slice(0, 3)
  const regularPlugins = (plugins || []).filter(plugin => !plugin.featured)

  if (isLoading && (!plugins || plugins.length === 0)) {
    return (
      <div className="space-y-6">
        <div className="text-center py-12">
          <LoadingSkeleton lines={3} />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <Card key={i} className="p-6">
              <LoadingSkeleton lines={4} avatar />
            </Card>
          ))}
        </div>
      </div>
    )
  }

  return (
    <ErrorBoundary>
      <div className="space-y-8">
        {/* Hero Section */}
        <div className="text-center py-12 bg-gradient-to-r from-primary-600 to-purple-600 rounded-lg text-white">
          <h1 className="text-4xl font-bold mb-4">{t('marketplace.title')}</h1>
          <p className="text-xl text-primary-100 mb-8 max-w-2xl mx-auto">
            {t('marketplace.subtitle')}
          </p>

          {/* Search Bar */}
          <div className="max-w-2xl mx-auto">
            <div className="relative">
              <Input
                placeholder={t('marketplace.searchPlaceholder')}
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                leftIcon={<MagnifyingGlassIcon />}
                className="text-gray-900 bg-white"
                fullWidth
              />
            </div>
          </div>
        </div>

        {/* Categories */}
        <div className="space-y-4">
          <h2 className="text-xl font-semibold text-gray-900">{t('marketplace.browseByCategory')}</h2>
          <div className="flex flex-wrap gap-3">
            {categories.map((category) => (
              <button
                key={category.id}
                onClick={() => setSelectedCategory(category.id)}
                className={`flex items-center px-4 py-2 rounded-lg border transition-colors ${
                  selectedCategory === category.id
                    ? 'bg-primary-50 border-primary-200 text-primary-700'
                    : 'bg-white border-gray-200 text-gray-700 hover:bg-gray-50'
                }`}
              >
                <span className="mr-2">{category.icon}</span>
                {t(category.nameKey)}
              </button>
            ))}
          </div>
        </div>

        {/* Filters and Sort */}
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <div className="flex items-center space-x-4">
            <Button
              variant="outline"
              onClick={() => setShowFilters(!showFilters)}
              icon={<FunnelIcon />}
            >
              Filters
            </Button>
            <span className="text-sm text-gray-600">
              {(plugins || []).length} plugins found
            </span>
          </div>

          <div className="flex items-center space-x-2">
            <label className="text-sm text-gray-600">Sort by:</label>
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="form-select text-sm"
            >
              {sortOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {t(option.labelKey)}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Featured Plugins */}
        {featuredPlugins.length > 0 && (
          <div className="space-y-4">
            <div className="flex items-center space-x-2">
              <FireIcon className="h-6 w-6 text-orange-500" />
              <h2 className="text-xl font-semibold text-gray-900">{t('marketplace.featured')}</h2>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {featuredPlugins.map((plugin) => (
                <Card key={plugin.id} className="p-6 hover:shadow-lg transition-shadow border-2 border-orange-200">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-2">
                        <h3 className="text-lg font-semibold text-gray-900">
                          {plugin.displayName}
                        </h3>
                        <Badge variant="warning" className="text-xs">
                          <SparklesIcon className="h-3 w-3 mr-1" />
                          {t('marketplace.featured')}
                        </Badge>
                      </div>
                      <p className="text-sm text-gray-600 mb-2">
                        {t('marketplace.by')} {plugin.developer?.displayName || plugin.developer?.username || t('marketplace.unknown')}
                      </p>
                      <StatusBadge status={plugin.status || 'pending'} />
                    </div>
                  </div>

                  <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                    {plugin.description || t('plugins.noDescription')}
                  </p>

                  <div className="flex items-center justify-between text-sm text-gray-500 mb-4">
                    <div className="flex items-center space-x-4">
                      <div className="flex items-center">
                        <ArrowDownTrayIcon className="h-4 w-4 mr-1" />
                        {plugin.totalDownloads.toLocaleString()}
                      </div>
                      <div className="flex items-center">
                        <StarIcon className="h-4 w-4 mr-1 text-yellow-400" />
                        {plugin.rating.average.toFixed(1)}
                      </div>
                    </div>
                    <div className="flex items-center">
                      <ClockIcon className="h-4 w-4 mr-1" />
                      {new Date(plugin.updatedAt).toLocaleDateString()}
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <Button
                      as={Link}
                      to={`/plugins/${plugin.id}`}
                      variant="primary"
                      size="sm"
                      className="flex-1"
                    >
                      {t('marketplace.viewDetails')}
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        )}

        {/* All Plugins */}
        <div className="space-y-4">
          <h2 className="text-xl font-semibold text-gray-900">
            {selectedCategory === 'all'
              ? t('marketplace.allPlugins')
              : t('marketplace.categoryPlugins', {
                  category: t(categories.find(c => c.id === selectedCategory)?.nameKey || 'marketplace.categories.all')
                })
            }
          </h2>

          {regularPlugins.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {regularPlugins.map((plugin) => (
                <Card key={plugin.id} className="p-6 hover:shadow-lg transition-shadow">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <h3 className="text-lg font-semibold text-gray-900 mb-2">
                        {plugin.displayName}
                      </h3>
                      <p className="text-sm text-gray-600 mb-2">
                        {t('marketplace.by')} {plugin.developer?.displayName || plugin.developer?.username || t('marketplace.unknown')}
                      </p>
                      <StatusBadge status={plugin.status || 'pending'} />
                    </div>
                  </div>

                  <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                    {plugin.description || t('plugins.noDescription')}
                  </p>

                  {/* Tags */}
                  {plugin.tags && plugin.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mb-4">
                      {plugin.tags.slice(0, 3).map((tag) => (
                        <Badge key={tag} variant="gray" size="sm">
                          {tag}
                        </Badge>
                      ))}
                      {plugin.tags.length > 3 && (
                        <Badge variant="gray" size="sm">
                          +{plugin.tags.length - 3}
                        </Badge>
                      )}
                    </div>
                  )}

                  <div className="flex items-center justify-between text-sm text-gray-500 mb-4">
                    <div className="flex items-center space-x-4">
                      <div className="flex items-center">
                        <ArrowDownTrayIcon className="h-4 w-4 mr-1" />
                        {plugin.totalDownloads.toLocaleString()}
                      </div>
                      <div className="flex items-center">
                        <StarIcon className="h-4 w-4 mr-1 text-yellow-400" />
                        {plugin.rating.average.toFixed(1)}
                      </div>
                    </div>
                    <div className="flex items-center">
                      <ClockIcon className="h-4 w-4 mr-1" />
                      {new Date(plugin.updatedAt).toLocaleDateString()}
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <Button
                      as={Link}
                      to={`/plugins/${plugin.id}`}
                      variant="outline"
                      size="sm"
                      icon={<EyeIcon />}
                      className="flex-1"
                    >
                      {t('common.view')}
                    </Button>
                  </div>
                </Card>
              ))}
            </div>
          ) : (
            <Card className="p-12 text-center">
              <div className="text-gray-400 mb-4">
                <MagnifyingGlassIcon className="mx-auto h-16 w-16" />
              </div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">{t('marketplace.noResults')}</h3>
              <p className="text-gray-600 mb-6">
                {t('marketplace.noResultsDescription')}
              </p>
              <Button
                onClick={() => {
                  setSearchTerm('')
                  setSelectedCategory('all')
                  setSortBy('downloads')
                }}
                variant="outline"
              >
                {t('marketplace.clearFilters')}
              </Button>
            </Card>
          )}
        </div>
      </div>
    </ErrorBoundary>
  )
}
